package com.invengo.device;

import com.invengo.uhf.ConnectType;
import com.invengo.uhf.RfidReader;

public class HandsetRfidReaderGenerator extends AbstractReader {

    /*
    channelType only for Bluetooth
     */
    private HandsetRfidReaderGenerator(ConnectType type, String port, int baudrate, int channelType){
        String connStr = "";
        if(type == ConnectType.RS232 || type == ConnectType.RS232Plus){
            connStr = String.format("%s,%s", port, String.valueOf(baudrate));
        }else if(type == ConnectType.Service){
            connStr = String.format("%s:%s", port, String.valueOf(baudrate));
        }else if(type == ConnectType.Bluetooth){
            connStr = port;
            setChannelType(channelType);
        }

        this.setRfidReader(new RfidReader.Builder().setType(type).setConnStr(connStr).setChannelType(channelType).builder());
    }

    @Override
    public boolean connect() {
        setConnected(this.getRfidReader().connect());
        return this.isConnected();
    }

    @Override
    public void disconnect() {
        this.getRfidReader().disconnect();
        this.setConnected(false);
    }

    public static class Builder{

        public ConnectType type;
        private int baudrate = 115200;
        private String port = "/dev/ttyMT1";
        private int channelType = RfidReader.RFID_CHANNEL_TYPE;

        public Builder(){

        }

        public Builder setType(ConnectType type){
            if(null == type){
                throw new IllegalArgumentException("Invalid parameter negative");
            }
            this.type = type;
            return this;
        }

        public Builder setBaudrate(int baudrate){
            if(baudrate < 0){
                throw new IllegalArgumentException("Invalid negative baudrate");
            }
            this.baudrate = baudrate;
            return this;
        }

        public Builder setPort(String port){
            if(null == port){
                throw new IllegalArgumentException("Invalid null port");
            }
            this.port = port;
            return this;
        }

        public Builder setChannelType(int channelType){
            if(channelType < 0 || channelType > 1){
                throw new IllegalArgumentException("Invalid range channelType");
            }
            this.channelType = channelType;
            return this;
        }

        public HandsetRfidReaderGenerator build(){
            return new HandsetRfidReaderGenerator(this.type, this.port, this.baudrate, this.channelType);
        }

    }
}
